<?php

class ControllerEventAutotranslater extends Controller
{
    public static $no_translate_key = ['href','addresses','code','languages','thumb'];
    public static $lang_map = ['en-gb' => 'en', 'zh-cn' => 'zh'];

    // catalog/view/*/before
    public function index(&$route, &$args, &$output)
    {
        $in_local = $this->config->get('config_autotrans_inlocal');
        $is_auto_trans = $this->config->get('config_is_auto_translate') && $this->config->get('config_trans_api_url') ? true : false; //是否开启自动翻译
        $break_route = ['common/','extension/'];
        $need_route = ['common/home','common/maintenance','extension/d_blog_module'];
        if (!$is_auto_trans || $in_local) {
            return;
        }
        $from = 'en';
        $to = $this->session->data['language'];
        foreach ($break_route as $item){
            if(stripos($route,$item) !== false && !$this->isNeedTrans($route,$need_route)){
                return;
            }
        }

        if (!empty(self::$lang_map[$to])) {
            $to = self::$lang_map[$to];
        }
        if ($from != $to) {
            $need_trans = [];
            $this->gettrans($args, $need_trans);
            $trans_data = $this->api_trans($need_trans, $from, $to);
            $i = 0;
            $this->translate($args, $trans_data, $i);
        }

    }

    private function isNeedTrans($route,$need_route){
        foreach ($need_route as $item){
            if(stripos($route,$item) !== false){
                return true;
            }
        }
        return false;
    }

    private function gettrans($data, &$ret)
    {
        if (is_array($data) && !empty($data)) {
            foreach ($data as $k => $v) {
                if (is_string($k) && in_array($k, self::$no_translate_key)) {
                    continue;
                }
                if (is_array($v)) {
                    $this->gettrans($v, $ret);
                } else if (is_string($v) && !empty($v)) {
                    $ret[] = $v;
                }
            }
        }
    }

    private function translate(&$data, $need_trans, &$i)
    {
        if (is_array($data) && !empty($data)) {
            foreach ($data as $k => $v) {
                if (is_string($k) && in_array($k, self::$no_translate_key)) {
                    continue;
                }
                if (is_array($v)) {
                    $data[$k] = $this->translate($v, $need_trans, $i);
                } else if (is_string($v) && !empty($v)) {
                    $data[$k] = $need_trans[$i]??$v;
                    $i++;
                }
            }
        }
        return $data;
    }

    private function api_trans($v, $from, $to)
    {
        $data = $this->translater->get($v, $from, $to);
        return $data;
    }
}